from django.shortcuts import render,reverse,redirect
from django.contrib import auth
from .forms import LoginForm,RegForm
from django.contrib.auth.models import User
from django.contrib.auth import logout

#主页
def index(request):
    context = {}
    return render(request,'index.html',context)


#验证登录
def login(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)  # loginfrom的实例对象
        if login_form.is_valid():  # 数据有效
            user = login_form.cleaned_data['user']  # 获取user信息
            auth.login(request, user)  # 登录
            return redirect(request.GET.get('from', reverse('index')))

    else:
        login_form = LoginForm()
    context = {}
    context['login_form'] = login_form
    return render(request, 'login.html', context)

# 进行注册
def register(request):
    if request.method == 'POST':
        reg_form = RegForm(request.POST)    #loginfrom的实例对象
        if reg_form.is_valid():
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']
            #创建用户
            user = User.objects.create_user(username,email,password)
            user.save()
            #登录用户
            user = auth.authenticate(username=username,password=password)
            auth.login(request,user)
            return redirect(request.GET.get('from', reverse('index')))
    else:
        reg_form = RegForm()
    context = {}
    context['reg_form'] = reg_form
    return render(request,'register.html',context)

# 注销
def exit(request):
    logout(request) #注销用户
    return redirect(request.GET.get('from', reverse('index')))